<script setup>
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import {ref} from "vue";
import { onMounted } from 'vue';

import md5 from 'js-md5'
import { resetInformationService,resetFirstInformationService } from '@/api/user/user';
onMounted(() => {
  FirstValidate();
});
const router = useRouter()
const userStore = useUserStore()

//退出登录
const logout=()=>{
    //清除保存在userStore中的用户信息
    userStore.removeName()
    userStore.removeToken()
    userStore.removeRoleId()
    userStore.removeJobNumber()
    localStorage.removeItem('user')
    //跳转回登录页
    router.push('/login')
}
let jobId = localStorage.getItem("jobNumber") ? JSON.parse(localStorage.getItem("jobNumber")) : null;
let password = localStorage.getItem("password") ? JSON.parse(localStorage.getItem("password")) : null;
let first = localStorage.getItem("first") ? JSON.parse(localStorage.getItem("first")) : null;
//修改资料
const changeForm = ref({
  jobNumber: '',
  email:'',
  password:'',
  password_repeat:'',
  first:''
});
//点击消息
const handleMessage = () => {
}
let flag =ref(0)
let flag2 =ref(0)
let passwordValid1 = false
let passwordValid2 = false
let passwordMismatch = false
let emailValid = false
const EmailValidate = () => {
  console.log('Validating email...')
  flag2=1
  const regexEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/
  emailValid = regexEmail.test(changeForm.value.email)
  console.log(changeForm.value.email)
}
const validatePassword = () => {
  //console.log('Validating password...')
  flag=1
  const regex1 = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&.#])[A-Za-z\d@$!%*?&.#]+$/
  const regex2 = /^.{6,8}$/
  passwordValid1 = regex1.test(changeForm.value.password)
  passwordValid2 = regex2.test(changeForm.value.password)
  //console.log(loginForm.value.password)
}

const checkPasswordMatch = () => {
  console.log('Checking password match...')
  passwordMismatch = changeForm.value.password_repeat !== changeForm.value.password
}

//修改资料
const showModal = ref(false)

//修改资料弹窗
const FirstValidate=()=>{

  // 获取 jobNumber 的后六位
  const lastSixDigits = jobId.slice(-6);
  // 对后六位进行 MD5 加密
  const encryptedPassword = md5(lastSixDigits);
  if(first==0){
    showModal.value=true;
  }
  else if(password==encryptedPassword){
    showModal.value=true;
  }
}
const SaveChange=async()=>{
  console.log("修改资料")
  if(first==0)
    {  
       first=1;
      const encryptedPassword = md5(changeForm.value.password);
      // 将加密后的密码设置回表单对象
      changeForm.value.password = encryptedPassword;
      const {data:res}=await resetFirstInformationService (changeForm.value.email,changeForm.value.password,jobId,first)
      console.log("修改资料的返回值");
      console.log(res)
      // if(res.code==0)
      // {
      //     message.error(res.data.message)
      // }
      // if(res.code==1)
      // {
      //     message.success(res.data.message)
      // }
    }
  else{
    const encryptedPassword = md5(changeForm.value.password);
      // 将加密后的密码设置回表单对象
      changeForm.value.password = encryptedPassword;
      const {data:res}=await resetInformationService (changeForm.value.email,changeForm.value.password,jobId)
      console.log("修改资料的返回值");
      console.log(res)
      // if(res.code==0)
      // {
      //     message.error(res.data.message)
      // }
      // if(res.code==1)
      // {
      //     message.success(res.data.message)
      // }
  }

}
</script>

<template>
  <div class="status-bar">
        <img src="@/assets/logo2.png" alt="学校图标">
        <span class="title">教学成果管理系统</span>
        <div class="profile"> 
            <n-space justify="end">
                <span style="margin-right: 1em;line-height: 34px">欢迎，{{userStore.name}}</span>
                    <n-button text @click="handleMessage">
                        <n-badge value="6" :max="15" style="margin-top: 8px; height: 18px; ">消息
                    </n-badge>
                </n-button>
                <n-button quaternary @click="showModal=true"> 修改资料</n-button>
                <n-button quaternary @click="logout">退出登录</n-button>
            </n-space>
        </div>
  </div>
  <!-- 修改资料模态框 -->
  <n-modal v-model:show="showModal"
            :close-on-esc="false"
            :mask-closable="false"
            :auto-focus="false">
    <n-card
      style="width: 650px"
      title="修改资料"
      bordered
      size="huge"
      role="dialog"
      aria-modal="true"
      closable
      @close="showModal=false"
    >
      <div class="container" >
        <div class="changeForm" style="width: 450px;background-color:white;border-radius: 5px;">
          <div class="title">重置密码</div>
          <form>
            <label for="username">邮箱</label>
            <n-input type="text" placeholder="请输入学校邮箱" id="useremail" v-model:value="changeForm.email"  @input="EmailValidate"></n-input>
            <div v-if="!emailValid&&flag2" style="color: red; margin-top: 5px;" >
              请输入合法的邮件地址
            </div>
            <label for="password">新密码</label>
            <n-input type="password" placeholder="请输入新密码" id="userpassword" v-model:value="changeForm.password" @input="validatePassword"></n-input>
            <div v-if="flag" style="color: red; margin-top: 5px;">
              <div v-if="!passwordValid1&&passwordValid2">
                密码必须包含大、小写字母、数字和特殊字符@$!%*?&.#
              </div>
              <div v-if="passwordValid1&&!passwordValid2">
                密码长度6-18位
              </div>
              <div v-if="!passwordValid1&&!passwordValid2">
                密码必须包含大、小写字母、数字和特殊字符
                密码长度6-18位
              </div>
            </div>
            <label for="password_repeat">重复密码</label>
            <n-input type="password" placeholder="请再次输入新密码" id="password_repeat" v-model:value="changeForm.password_repeat" prop="password_repeat" @input="checkPasswordMatch"></n-input>
            <div v-if="passwordMismatch" style="color: red;margin-top: 5px;">两次密码不一致</div>
            <n-button :disabled="passwordMismatch" @click="SaveChange()">保存</n-button>
          </form>
        </div>
      </div>
    </n-card>
  </n-modal>
</template>

<style scoped>
.status-bar{
    width: auto;
    height: 100px;
    background: linear-gradient(to right, rgb(5,93,163), rgb(255,255,255));
    display: flex;
    align-items: center;
    padding: 10px;
    color: rgba(22, 22, 22, 0.619);
}
img{
    
    height:90px;
    margin-left: 30px;
    
}
 .title{
    margin-left:20px ;
    width:300px;
    line-height: 50px;
    color:white;
    font-size: 30px;
    letter-spacing: .2em;
    font-family: 楷体,楷体_GB2312;
}
.profile{
    /**分配剩余空间位置  <1*/
    flex-grow: 1;
    text-align: right;
}
form{
  width: auto;
  padding: 0 30px;
  box-sizing:border-box;
}
label {
  display: block;
  margin-top: 30px;
  font-size: 16px;
}
input {
  display: block;
  height: 45px;
  width: 100%;
  border-radius: 5px;
  padding: 0 10px;
  margin-top: 8px;
  font-size: 14px;
  font-weight: 300;
  box-sizing:border-box;
  border: 1px solid rgb(218, 210, 210);
}
.alink {
  text-align: right;
  color: inherit; 
  transition: all 0.3s; 
  text-decoration: none;
  color: grey;
}
.alink:hover{
    /* 当鼠标悬停时 */
    color: #007bff; 
    text-decoration: underline; 
}
</style>
